package com.dc.web.controller;

import com.dc.constant.Constants;
import com.dc.constant.MessageConstant;
import com.dc.entity.UserEntity;
import com.dc.dao.UserDao;
import com.dc.model.AjaxResult;
import com.dc.model.ResetPasswordBody;
import com.dc.model.UserListSearchBody;
import com.dc.service.JwtTokenService;
import com.dc.service.UserService;
import com.dc.utils.PasswordEncryUtil;
import net.minidev.json.JSONArray;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Optional;

@RequestMapping("/api/user")
@RestController
public class UserController {

    @Resource
    JwtTokenService tokenService;

    @Resource
    UserService userService;

    @Resource
    UserDao sysUserDao;

    /**
     * 根据用户名搜索
     * @param userListSearchBody
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(UserListSearchBody userListSearchBody) {

        Integer pageNumber = userListSearchBody.getPageNumber();
        pageNumber = ObjectUtils.defaultIfNull(pageNumber, 1);
        Integer pageSize = userListSearchBody.getPageSize();
        pageSize = ObjectUtils.defaultIfNull(pageSize, 20);
        String name = userListSearchBody.getName();

        PageRequest pageRequest = PageRequest.of(pageNumber - 1, pageSize);

        Page<UserEntity> users = null;

        if(ObjectUtils.isEmpty(name)) {
            users = sysUserDao.findAll(pageRequest);
        } else {
            users = sysUserDao.findSysUsersByName(name, pageRequest);
        }
        return AjaxResult.success(users);
    }

    @GetMapping("/current")
    public AjaxResult current(@RequestHeader HttpHeaders httpHeaders) {
        UserEntity user = userService.getUser(httpHeaders);
        return AjaxResult.success(user);
    }

    /**
     * 新增新用户
     * @param sysUser
     * @return
     */
    @PostMapping()
    public AjaxResult add(@RequestBody @Validated UserEntity sysUser) {
        if(ObjectUtils.isEmpty(sysUser)) {
            return AjaxResult.error(MessageConstant.ERR_USER_IS_NULL);
        }
        boolean b = sysUserDao.existsSysUserByUserName(sysUser.getUserName());
        if(b) {
            return AjaxResult.error(MessageConstant.ERR_USER_NAME_IS_EXIST);
        }
        String username = sysUser.getUserName();
        String password = sysUser.getPassword();
        String role = sysUser.getRole();
        if(ObjectUtils.isEmpty(role)) {
            sysUser.setRole(Constants.DEFAULT_ROLE);
        }
        sysUser.setId(null);
        sysUser.setPassword(PasswordEncryUtil.md5Hex(username, password));
        UserEntity user = sysUserDao.save(sysUser);
        return AjaxResult.success(user);
    }

    /**
     * 更新用户
     * @param id
     * @param sysUser
     * @return
     */
    @PutMapping("/{id}")
    public AjaxResult update(@PathVariable("id") Long id, @RequestBody @Validated UserEntity sysUser) {
        sysUser.setId(id);
        Optional<UserEntity> beanInDB = sysUserDao.findById(id);
        String passwordInParam = sysUser.getPassword();
        String username = sysUser.getUserName();

        String passwordInDB = "";
        if(beanInDB.isPresent()) {
            UserEntity user = beanInDB.get();
            passwordInDB = user.getPassword();
        }

        if(!passwordInParam.equals(passwordInDB)) { // 输入的内容和数据库密码不一致，则加密
            sysUser.setPassword(PasswordEncryUtil.md5Hex(username, passwordInParam));
        }
        if(!sysUser.getWorkFlows().isEmpty()){
            sysUser.setMenus(JSONArray.toJSONString(sysUser.getWorkFlows()));
        }
        UserEntity user = sysUserDao.save(sysUser);
        return AjaxResult.success(user);
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@RequestHeader HttpHeaders httpHeaders, @PathVariable("id") Long id) {
        UserEntity user = userService.getUser(httpHeaders);
        if(user.getId().equals(id)) {
            return AjaxResult.error(MessageConstant.ERR_DELETE_CURRENT_USER); // 当前用户不允许删除
        }
        sysUserDao.deleteById(id);
        return AjaxResult.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/resetPassword")
    public AjaxResult resetPassword(@RequestHeader HttpHeaders httpHeaders, @RequestBody @Validated ResetPasswordBody resetPasswordBody) {
        String password = resetPasswordBody.getPassword();
        String confirmPassword = resetPasswordBody.getConfirmPassword();
        if(password.equals(confirmPassword)) {
            UserEntity user = userService.getUser(httpHeaders);
            String userName = user.getUserName();
            password = PasswordEncryUtil.md5Hex(userName, password);
            sysUserDao.updatePasswordById(user.getId(), password);
            return AjaxResult.success();
        } else {
            return AjaxResult.error(MessageConstant.ERR_PASSWORD_DOUBLE);
        }

    }


}
